package com.yuyunbo.es.restclient.autoconfigure;

import com.yuyunbo.es.restclient.EsApiService;
import com.yuyunbo.es.restclient.EsModel;
import com.yuyunbo.es.restclient.constants.EsConstants;
import com.yuyunbo.es.restclient.query.*;
import com.yuyunbo.es.restclient.util.AnnotationUtil;
import com.yuyunbo.es.restclient.util.EsException;
import com.yuyunbo.es.restclient.vo.EsQueryBaseVO;
import com.yuyunbo.es.restclient.vo.EsScrollQueryResponse;
import com.yuyunbo.es.restclient.vo.PageBean;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yuyunbo-1154363414@qq.com
 * @Date: 2019/1/25 14:32
 * @Description:
 */
public class EsApiServiceImpl implements EsApiService {
    @Autowired
    private EsRestClient esRestClient;

    /**
     * 根据基类获取 推送ES模型类
     *
     * @param dataModel
     * @return
     */
    @Override
    public <T> EsModel<T> getPutEsModel(T dataModel) {
        String[] strArray = getEsIndexType(dataModel, true);
        EsModel<T> esModel = new EsModel<T>();
        esModel.setEsIndex(strArray[0]);
        esModel.setEsType(strArray[1]);
        esModel.setMonthIndex(Boolean.valueOf(strArray[2]));
        return esModel;
    }

    private <T> String[] getEsIndexType(T dataModel, boolean isPustData) {
        String indexAndType = AnnotationUtil.getESIndexValue(dataModel, isPustData);
        if (StringUtils.isEmpty(indexAndType)) {
            throw new RuntimeException("EsIndexKey 注解不存在");
        }
        String[] strArray = indexAndType.split(EsConstants.SPLIE_KEY);
        if(strArray.length != 3){
            throw new EsException("EsIndexKey 属性不正确");
        }
        for (String value : strArray) {
            if (StringUtils.isEmpty(value)) {
                throw new EsException("索引和类型不能为空");
            }
        }
        return strArray;
    }

    /**
     * 根据基类获取 查询ES模型类
     *
     * @param esQueryBaseVO
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public <T> EsModel<T> getSerachEsModel(EsQueryBaseVO esQueryBaseVO, int page, int pageSize) {
        String[] strArray = getEsIndexType(esQueryBaseVO, false);
        EsModel<T> esModel = new EsModel<T>();
        esModel.setEsIndex(strArray[0]);
        esModel.setEsType(strArray[1]);
        esModel.setMonthIndex(Boolean.valueOf(strArray[2]));
        esModel.setPage(page);
        esModel.setPageSize(pageSize);
        getEsSort(esQueryBaseVO, esModel);
        getMatchParams(esQueryBaseVO, esModel);
        getShouldParams(esQueryBaseVO, esModel);
        getTermsParams(esQueryBaseVO, esModel);
        getRangeParams(esQueryBaseVO, esModel);
        return esModel;
    }

    private <T> void getMatchParams(EsQueryBaseVO esQueryBaseVO, EsModel<T> esModel) {
        Map<String, String> map = AnnotationUtil.getEsMatchColumnValue(esQueryBaseVO);
        EsMatchQuery esMatchQuery = new EsMatchQuery();
        esMatchQuery.setMatch(map);
        esModel.setEsMatchQuery(esMatchQuery);
    }

    private <T> void getShouldParams(EsQueryBaseVO esQueryBaseVO, EsModel<T> esModel) {
        Map<String, List<String>> map = AnnotationUtil.getEsShouldColumnValue(esQueryBaseVO);
        EsShouldListQuery esMatchlistQuery = new EsShouldListQuery();
        esMatchlistQuery.setMatch(map);
        esModel.setEsShouldListQuery(esMatchlistQuery);
    }

    private <T> void getTermsParams(EsQueryBaseVO esQueryBaseVO, EsModel<T> esModel) {
        Map<String, List<String>> map = AnnotationUtil.getEsTermsColumnValue(esQueryBaseVO);
        EsTermsQuery esTermsQuery = new EsTermsQuery();
        esTermsQuery.setTerms(map);
        esModel.setEsTermsQuery(esTermsQuery);
    }

    private <T> void getRangeParams(EsQueryBaseVO esQueryBaseVO, EsModel<T> esModel) {
       List<EsRangeQuery> rangeQueryList = AnnotationUtil.getEsRangeColumnValue(esQueryBaseVO);

       if (CollectionUtils.isNotEmpty(rangeQueryList)) {
            esModel.setRangList(rangeQueryList);
        }
    }

    private <T> void getEsSort(EsQueryBaseVO esQueryBaseVO, EsModel<T> esModel) {
        Map<String, String> sortMap = AnnotationUtil.getEsSortColumnValue(esQueryBaseVO);
        if (sortMap.isEmpty()) {
            return;
        }
        List<Map<String, EsSort>> sort = new ArrayList<>();
        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            String esSortValue = entry.getKey();
            if (StringUtils.isEmpty(esSortValue)) {
                throw new EsException("排序注解中的，排序字段和排序方式不能为空");
            }
            Map<String, EsSort> esSortMap = new HashMap<>();
            EsSort esSort = new EsSort();
            esSort.setOrder(entry.getValue());
            esSortMap.put(esSortValue, esSort);
            sort.add(esSortMap);
        }
        esModel.setSort(sort);
    }

    /**
     * 分页查询
     *
     * @param esModel@return
     */
    @Override
    public <T> PageBean<T> getPageBean(EsModel<T> esModel, Class<T> requiredType) {
        checkSerachPageParam(esModel);
        return esRestClient.queryPage(esModel, requiredType);
    }

    /**
     * 单个提交保存到ES
     *
     * @param esModel
     */
    @Override
    public <T> void putToEs(EsModel<T> esModel) {
        checkPutToEs(esModel);
        esRestClient.putToEs(esModel);
    }


    /**
     * 查询List 集合
     *
     * @param esModel
     * @return
     */
    @Override
    public <T> List<T> queryList(EsModel<T> esModel, Class<T> requiredType) {
        checkSerachPageParam(esModel);
        return esRestClient.queryList(esModel, requiredType);
    }

    /**
     * 统计数据条数
     *
     * @param esModel
     * @return
     */
    @Override
    public <T> int queryCount(EsModel<T> esModel) {
        checkSerachPageParam(esModel);
        return esRestClient.queryCount(esModel);
    }

    /**
     * 批量提交保存到ES
     *
     * @param esModel
     */
    @Override
    public <T> void batchPutToEs(final EsModel<T> esModel) {
        checkBatchPutToEs(esModel);
        esRestClient.batchPutToEsList(esModel);
    }

    @Override
    public <T> EsScrollQueryResponse<T> openScrollSearch(EsModel<T> esModel, int aliveSeconds, Class<T> requiredType) {
        checkBatchPutToEs(esModel);
        return esRestClient.openScrollSearch(esModel,aliveSeconds,requiredType);
    }

    @Override
    public <T> EsScrollQueryResponse<T> searchByScrollId(String scrollId, int aliveSeconds, Class<T> requiredType) {
        return esRestClient.searchByScrollId(scrollId,aliveSeconds,requiredType);
    }

    private <T> void checkPutToEs(EsModel<T> esModel) {
        checkSerachPageParam(esModel);
        if (esModel.getData() == null) {
            throw new EsException("保存的数据不能为空");
        }
    }

    private <T> void checkBatchPutToEs(EsModel<T> esModel) {
        checkSerachPageParam(esModel);
        if (esModel.getListData() == null || esModel.getListData().size() == 0) {
            throw new EsException("保存的数据不能为空");
        }
    }

    /**
     * 基础校验
     *
     * @param esModel
     * @param <T>
     */
    private <T> void checkSerachPageParam(EsModel<T> esModel) {
        String type = esModel.getEsType();
        String indexname = esModel.getEsIndex();
        if (StringUtils.isEmpty(indexname)) {
            throw new EsException("索引不能为空");
        }
        if (StringUtils.isEmpty(type)) {
            throw new EsException("类型不能为空");
        }
    }
}
